import 'package:get/get.dart';

class CustomDateUtils {
  CustomDateUtils._();

  static String formatDuration(int seconds) {
    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;
    final remainingSeconds = seconds % 60;

    final hoursString = hours > 0 ? '${hours.toString().padLeft(2, '0')}:' : '';
    final minutesString = '${minutes.toString().padLeft(2, '0')}:';
    final secondsString = remainingSeconds.toString().padLeft(2, '0');

    return '$hoursString$minutesString$secondsString';
  }

  static String formatTimestamp(int? timestamp, {bool withTime = false}) {
    if (timestamp == null) return '';

    final now = DateTime.now();
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = DateTime(now.year, now.month, now.day - 1);
    final dateOnly = DateTime(date.year, date.month, date.day);

    // 时间部分（使用基础Dart功能）
    final timeStr = _formatTime(date);

    // 日期逻辑
    String dateStr;
    if (dateOnly == today) {
      dateStr = timeStr; // 今天只显示时间
    } else if (dateOnly == yesterday) {
      dateStr = '${'common.yesterday'.tr} $timeStr';
    } else if (now.difference(dateOnly).inDays < 7) {
      dateStr = _getWeekday(date); // 使用翻译的周几
    } else if (date.year == now.year) {
      dateStr = _formatMonthDay(date);
    } else {
      dateStr = _formatFullDate(date);
    }

    // 处理时间显示
    final shouldAddTime = withTime &&
        !dateStr.contains(timeStr) &&
        dateStr != timeStr;

    return shouldAddTime ? '$dateStr $timeStr' : dateStr;
  }

  // --- 以下是纯Dart实现的辅助方法 ---
  static String _formatTime(DateTime date) {
    return '${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
  }

  static String _getWeekday(DateTime date) {
    final weekdays = [
      'common.sunday'.tr,
      'common.monday'.tr,
      'common.tuesday'.tr,
      'common.wednesday'.tr,
      'common.thursday'.tr,
      'common.friday'.tr,
      'common.saturday'.tr,
    ];
    return weekdays[date.weekday % 7];
  }

  static String _formatMonthDay(DateTime date) {
    return '${date.month}-${date.day}';
  }

  static String _formatFullDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}